package com.erp.erp_ui.Ftp;

import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName FtpControl
 * @Description FTP服务
 * @Author songjizhen
 * @Date 2020-06-30 20:25
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "ftp")
public class FtpControl extends Base {
    @Autowired
    IFtpService ftpService;
    private static String ALLPATH="/data0/AllPath";
    private static String ONLINEPATH="";
    static {
        if(OSUtils.isOSLinux()){
            ALLPATH="/data0/AllPath";
            Properties ftp = PropertiesUtils.loadProperties("ftp");
            ONLINEPATH= ftp.getProperty("onlineFileLinux");
        }
        if(OSUtils.isOSWin()){
            ALLPATH=OSUtils.getHome();
            ALLPATH=ALLPATH.substring(0,ALLPATH.length()-1);
            ALLPATH= ALLPATH.replaceAll("\\\\","/");
            ONLINEPATH=ALLPATH;
        }
        System.out.println("ALLPATH"+ALLPATH);
    }
    /**
     * 上传文件
     * @param request
     * @param fileType 文件业务属性（即文件是在哪个业务模块中的，用于组装在文件服务器上的路径）
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadFile" ,method = RequestMethod.POST, consumes = "multipart/*")
    @ResponseBody
    public R<List<UploadFile>> uploadFile(MultipartHttpServletRequest request,String fileType) throws Exception{//
        try{
            String ftppath=this.getFtpPath();
            List<UploadFile> upload = ftpService.upload(request, fileType, ftppath);
            return R.build(upload);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.UPLOAD_FILE_ERROR);
        }
    }
    /**
     * 上传文件
     * @param path 在linux上的绝对地址
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "ftpuploadFile" ,method = RequestMethod.POST, consumes = "multipart/*")
    @ResponseBody
    public void ftpuploadFile(String path) throws Exception{//
        try{
            ftpService.ftpUpload(path);
        }catch (Exception e){
            e.printStackTrace();

        }
    }
    /**
     * ftp路径，/upload/部门编码/员工编码       这里存在问题
     * @return
     */
    private String getFtpPath(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            String code = user.getCode();
            String departmentCode = user.getDepartmentCode();
            return ALLPATH+"/upload/"+departmentCode+"/"+code+"/"+ System.currentTimeMillis();
        }catch (Exception e){
            e.printStackTrace();
            return ALLPATH+"/upload";
        }

    }
    /**
     * ftp路径，/upload/部门编码/员工编码       这里存在问题
     * @return
     */
    private String getFtpPath2(){
        try {
            UserEntity user = (UserEntity)this.getBean("user");
            String code = user.getCode();
            String departmentCode = user.getDepartmentCode();
            return "/upload/"+departmentCode+"/"+code+"/"+ System.currentTimeMillis();
        }catch (Exception e){
            e.printStackTrace();
            return "/upload";
        }

    }
    /**
     * 下载文件 *
     *

     * @param filename  文件名称wg

     * @return
     */
    @RequestMapping(value = "downloadfile" ,method = RequestMethod.POST)
    @ResponseBody

    public void downloadfile(String filename, HttpServletRequest request,HttpServletResponse response) throws Exception{//String pathname, String filename,String localpath
        // ftpService.downloadFile(pathname, filename, localpath);
        FtpOperationUtil ftp=new FtpOperationUtil();
        ftp.download(filename,response,request);
    }

    /**
     * 图片输入到页面，用于展示
     *      *   在html中直接在img标签的src属性值为controller的请求地址即可。
     * @param pathname ftp上的路径
     * @param filename  ftp上的文件名
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "downloadimg")
    @ResponseBody

    public void downloadimg(String pathname,String filename,HttpServletResponse response) throws Exception {
        // String pathname="/ftp";
        // String filename="大数据面试总结.png";
            ftpService.download(pathname, filename, response);
    }
    @RequestMapping(value = "downloadimg2")
    @ResponseBody
    public void downloadimg2(String url,HttpServletResponse response) throws Exception {
        String filename=url.substring(url.lastIndexOf("/")+1);
        String pathname=url.substring(0,url.lastIndexOf("/"));
        ftpService.download(pathname, filename, response);
    }


    @RequestMapping(value = "onLineonLine")
    @ResponseBody
    public R<String> onLineonLine(String pathString,HttpServletResponse response)throws Exception{
        try {
            String filename=pathString.substring(pathString.lastIndexOf("/")+1);
           // filename = System.currentTimeMillis() + filename;
            org.apache.commons.io.FileUtils.copyFile(new File(pathString), new File(ONLINEPATH+"/"+filename));
            return R.build( filename);
        }catch (Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
        return R.build("");
    }
    @RequestMapping(value = "onLineonLineEmail")
    @ResponseBody
    public R<String> onLineonLineEmail(String pathString,String filename,HttpServletResponse response)throws Exception{
        try {
            // filename = System.currentTimeMillis() + filename;
            org.apache.commons.io.FileUtils.copyFile(new File(pathString), new File(ONLINEPATH+"/"+filename));
            return R.build( filename);
        }catch (Exception e){
            System.out.println(e);
            e.printStackTrace();
        }
        return R.build("");
    }
    @RequestMapping(value = "onLine2")
    @ResponseBody
    public String onLine2(String pathString,HttpServletResponse response)throws Exception{
        String pathname=pathString.substring(0,pathString.lastIndexOf("/"));
        String filename=pathString.substring(pathString.lastIndexOf("/")+1);
        Properties properties = PropertiesUtils.loadProperties("ftp");
        File[] onlines = FileUtils.getDir(properties.getProperty("online2"));
        String d=DateUtils.format(new Date(),DateUtils.DATE_PATTERN);
        // return file;
        File file2 = new File(properties.getProperty("online2")+d+pathname);
        //判断目标文件目录是否存在
        if(!file2.exists()){
            file2.mkdirs();
        }
        for(int i=0;i<onlines.length;i++){
            if(!onlines[i].getName().equals(d)){
                FileUtils.delete(onlines[i].getAbsolutePath());
            }

        }
        //String online = properties.getProperty("online");
        String path=properties.getProperty("online2")+d+pathname;;//resource.getPath()+"wjtem/";
        FtpUtils ftp=new FtpUtils();
        boolean b = ftp.downloadFile(pathname, filename,path );

        return d+pathname+"/"+filename;
    }

}
